package controler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Academy;
import model.Subject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.upload.FormFile;

import controler.forms.MapForm;

public class ConceptualMapAction extends MappingDispatchAction {
	
	public final String DEFAULT = "default";
	
	/**
	 * Guarda en db archivo mapa_conceptual
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward upload(
			ActionMapping mapping, 
			ActionForm form, 
			HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		ActionForward action_retVal = Validate.validateUser(mapping,request, getResources(request));
    	if(action_retVal!=null)return action_retVal;
    	String str_academyCode = request.getParameter("academy_id");
    	String str_subjectCode = request.getParameter("subject_id");
    	request.setAttribute("academia", Academy.instance(str_academyCode));
    	request.setAttribute("materia", Subject.instance(str_subjectCode, str_academyCode));
    	
		MapForm forma = (MapForm)form;
		FormFile file = forma.getFile();
		
		String str_filename    = file.getFileName();
		byte[] byte_file       = file.getFileData();
		business.MapaConceptual.upload(str_subjectCode, byte_file, str_filename);
		request.setAttribute("req_msg", getResources(request).getMessage("map.uploadFileSuccess"));
		return view(mapping, form, request, response);
	}
	
	
	/**
	 * Vista de Mapa Conceptual
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward view(
			ActionMapping mapping, 
			ActionForm form, 
			HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		
		ActionForward action_retVal = Validate.validateUser(mapping,request, getResources(request));
    	if(action_retVal!=null)return action_retVal;
    	String str_academyCode = request.getParameter("academy_id");
    	String str_subjectCode = request.getParameter("subject_id");
    	request.setAttribute("academia", Academy.instance(str_academyCode));
    	request.setAttribute("materia", Subject.instance(str_subjectCode, str_academyCode));
    	String str_path = request.getRealPath("/tmp");
    	String str_file = model.ConceptualMap.view(str_subjectCode, str_path);
    	if( str_file != null && !str_file.equals("") ){
    		HttpSession session = request.getSession(); 
    		session.setAttribute("inst_mapaConceptual", "tmp/"+str_file);
    	}
		return mapping.findForward(DEFAULT);
	}	
}
